import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/HomePage.dart';
import 'package:flutter_enjoy_plus/pages/mine/MinePage.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({Key? key}) : super(key: key);

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  List tabsList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    }
  ];
  int activeIndex = 0;

  List<BottomNavigationBarItem> getTabsBar() {
    List<BottomNavigationBarItem> list = [];
    for (var i = 0; i < tabsList.length; i++) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(
            tabsList[i]['icon'],
            width: 30,
            height: 30,
          ),
          activeIcon: Image.asset(
            tabsList[i]['activeIcon'],
            width: 30,
            height: 30,
          ),
          label: tabsList[i]['label']));
    }
    return list;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tokenManager.init();
    regiterEventBus();
  }

  regiterEventBus() {
    eventBus.on<LogoutEvent>().listen((params) {
      Navigator.pushNamed(context, '/login');
    });
  }

  void updateIndex(int index) {
    activeIndex = index;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: activeIndex,
          children: [
            HomePage(),
            MinePage(
              currentIndex: activeIndex,
              updateIndex: updateIndex,
            )
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (index) {
          setState(() {
            activeIndex = index;
          });
        },
        items: getTabsBar(),
        type: BottomNavigationBarType.fixed,
        currentIndex: activeIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
      ),
    );
  }
}
